package com.hospital.hospital.controller;

import com.hospital.hospital.bean.Bill;
import com.hospital.hospital.bean.Drug;
import com.hospital.hospital.bean.User;
import com.hospital.hospital.service.BillService;
import com.hospital.hospital.service.DrugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author xfm
 * @create 2021/9/6
 */
@Controller
@SessionAttributes(types = {User.class,Drug.class})
@RequestMapping("/bill")
public class BillController {
    @Autowired
    public BillService billService;

    @Autowired
    public DrugService drugService;

    @RequestMapping("/buy")
    public String buy(Model model, HttpServletRequest request,Integer[] id,Integer[] many){

        try {
            Object user = request.getSession().getAttribute("user");
            request.setAttribute("user",user);
            User user1=(User) user;
            for (int i = 0; i < id.length; i++) {
                Drug  drug = drugService.queryById(id[i]);
                if(many[i]==null){
                    many[i]=0;
                }
                System.out.println(id[i]);
                System.out.println(drug.getNum());
                System.out.println(many[i]);
                drugService.reduce(id[i],drug.getNum()-many[i]);
                if(many[i] !=0){
                Bill bill=new Bill();
                bill.setName(user1.getName());
                bill.setDname(drug.getDname());
                bill.setSprice(drug.getSprice());
                bill.setPnum(many[i]);
                bill.setSum(many[i]*drug.getSprice());
                billService.insert(bill);}

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
          return "redirect:/bill/showUi";
    }
    @RequestMapping("/showUi")
    public String showUi(Model model,Double sum,HttpServletRequest request){
        try {
            sum=0.0;
            Object user = request.getSession().getAttribute("user");
            User user1=(User)user;
            model.addAttribute("user",user);
            List<Bill> bills = billService.show(user1.getName());
            model.addAttribute("bills",bills);
            for (Bill bill : bills) {
                sum = sum + bill.getSum();
            }
            model.addAttribute("sum",sum);}
        catch (Exception e) {
            e.printStackTrace();
        }
        return "bill";
    }

}
